<template>
    <div class="container">
        <div class="register">
            <h3>新用户注册</h3>
            <ul class="register-list">
                <li>
                    <div class="register-list-row">
                        <label class="register-row-title">
                            <span style="color:#ff4949">*</span>
                            公司代码
                        </label>
                        <div class="register-row-content">
                            <input type="text" placeholder="请输入公司代码" v-model="companyCode" @blur="initMendian">
                            <i class="fa fa-times-circle fa-hidden"></i>
                            <i class="fa fa-exclamation-circle"></i>
                        </div>
                        <button class="scan-btn" @click="sheetVisible=true;"><img src="./assets/images/scan.png" /> &nbsp;扫码</button>
                        <input type="file" class="fileBtn" @change="upload" name="files" id="files" ref="filElem">
                    </div>
                </li>
                <li>
                    <div class="register-list-row">
                        <label class="register-row-title">所属门店</label>
                        <div class="register-row-content">
                            <select class="md-select" v-on:change="initZubie" v-model="mendian" style="width: auto;">
                                <option value="">--请选择--</option>
                                <option :value="item.id" v-for="(item,index) in mendianList" :key="index" >{{item.departmentName}}</option>
                            </select>
                            <i class="fa fa-times-circle fa-hidden"></i>
                            <i class="fa fa-exclamation-circle"></i>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="register-list-row">
                        <label class="register-row-title">所属组别</label>
                        <div class="register-row-content">
                            <select class="md-select" v-model="zubie" style="width: auto;">
                                <option value="">--请选择--</option>
                                <option :value="item.id" v-for="(item,index) in zubieList" :key="index">{{item.departmentName}}</option>
                            </select>
                            <i class="fa fa-times-circle fa-hidden"></i>
                            <i class="fa fa-exclamation-circle"></i>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="register-list-row">
                        <label class="register-row-title"><span style="color:#ff4949">*</span>姓名</label>
                        <div class="register-row-content">
                            <input type="text" placeholder="请输入姓名" v-model="accountName" maxlength="11">
                            <i class="fa fa-times-circle "></i>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="register-list-row">
                        <label class="register-row-title"><span style="color:#ff4949">*</span>账号</label>
                        <div class="register-row-content">
                            <input type="tel" placeholder="请输入手机号" v-model="phone" maxlength="11">
                            <i class="fa fa-times-circle "></i>
                        </div>
                    </div>
                </li>
                <li>
                    <div class="register-list-row">
                        <label class="register-row-title"><span style="color:#ff4949">*</span>验证码</label>
                        <div class="register-row-content">
                            <input type="text" placeholder="请输入验证码" v-model="code">
                            <i class="fa fa-times-circle "></i>
                        </div>
                        <button  :class="codeDis ? 'verificationing':'verification'" v-bind:disabled="codeDis" @click="sendVerificationCode">{{verificationCode}}</button>
                    </div>
                </li>
            </ul>
            <button class="btn-register" @click="register" v-if="isShow">注册</button>
        </div>
        <mt-actionsheet
                :actions="actions"
                v-model="sheetVisible">
        </mt-actionsheet>
    </div>
</template>
<script>
    import { Actionsheet } from 'mint-ui';
    export default{
        components:{Actionsheet},
        data(){
            return {
                verificationCode:'发送验证码',
                timer:0,
                codeDis : false,
                accountName:'',
                code:'',//验证码
                phone:'',//手机号
                companyCode:'',//公司代码
                isShow:true,
                mendian: '',
                mendianList: [],
                zubie: '',
                zubieList: [],
                sheetVisible:false,
                actions:[{name:'本地照片识别',method:this.selectFile},{name:'扫描二维码',method:this.scanQRCode}]
            }
        },
        mounted: function() {
            //初始化数据
            this.verificationCodeTimer(true);
            this. wxConfig();
            if(this.$route.params.dept){
                this.analysisCode(this.$route.params.dept);
            }
        },
        activated:function(){
            //初始化数据
            this.verificationCodeTimer(true);
        },
        methods:{
            //发送验证码
            sendVerificationCode:function(){
                var _self = this;
                if(!_self.companyCode){
                    layer.msg("请输入公司代码");
                    return;
                }
                if(!_self.accountName){
                    layer.msg("请填写姓名");
                    return;
                }
                //验证手机号
                if(!_self.phone){
                    layer.msg("请填写手机号");
                    return;
                }
                if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(_self.phone))){
                    layer.msg("请填写正确的手机号");
                    return;
                }
                //设置不能点击
                _self.codeDis = "disabled";
                var params = {
                    phone:_self.phone,
                    companyCode:_self.companyCode
                };
                var body = {};
                body.params = params;
              //  layer.msg("短信发送成功，请注意查收");
                var url = this.utilHelper.apiUrl+'/api/sendVerificationCode';
                _self.$http.post(url,body).then((response) => {
                    var body = response.body;
                    if(body.result == 1){
                        layer.msg("短信发送成功，请注意查收");
                        _self.verificationCodeTimer(false);
                    }else{
                        layer.msg(body.errorMsg);
                        _self.verificationCodeTimer(false);
                    }
                }),(response => {
                   layer.msg("发送短信异常");
                });
            },
            //短信验证码定时器
            verificationCodeTimer:function(flag){
                var _self = this;
                var date = 0;
                if(flag){//页面刷新，或重进入时
                    if(window.sessionStorage.getItem("3_verification")){//若缓存中不存在数据则 不进行倒计时
                        date =  window.sessionStorage.getItem("3_verification");
                    }else{
                        return;
                    }
                }else{//点击发送按钮时
                    date = new Date().getTime() +1000*120;
                    window.sessionStorage.setItem("3_verification",date);
                    _self.timer = 120;
                }

                _self.codeDis = "disabled";
                var code = setInterval(function(){
                    _self.timer = Math.ceil((date - new Date().getTime())/1000);//向上取整数
                    if(_self.timer <= 0 ){
                        window.sessionStorage.removeItem("3_verification");
                        _self.verificationCode = '发送验证码';
                        _self.codeDis = false;
                        window.clearInterval(code);
                    }else{
                        _self.verificationCode = _self.timer + 'S';
                        _self.timer-=1;
                    }
                },1000);
            },

            //注册新用户（含绑定功能）
            register:function(){
                var _self = this;
                var params = {
                    accountName:_self.accountName,
                    phone:_self.phone,
                    verificationCode:_self.code,
                    companyCode:_self.companyCode,
                    mendian: _self.mendian,
                    zubie: _self.zubie
                }
                if(!_self.companyCode){
                    layer.msg("请输入公司代码");
                    return;
                }
                if(!params.accountName){
                    layer.msg("请填写姓名");
                    return;
                }
                //验证手机号
                if(!params.phone){
                    layer.msg("请填写手机号");
                    return;
                }
                if(!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(params.phone))){
                    layer.msg("请填写正确的手机号");
                    return;
                }
                if(!params.verificationCode){
                    layer.msg("请填写验证码");
                    return;
                }
                if(params.verificationCode.length > 6){
                    layer.msg("验证码填写不合法");
                    return;
                }
                _self.isShow = false;//隐藏注册按钮
                var body = {};
                body.params = params;
                var url = _self.utilHelper.apiUrl+'/api/regist';
                _self.$http.post(url,body).then((response) => {
                    var body = response.body.resData;
                    if(body.result == 1){
                        layer.msg(body.resultMsg, {
                            time: 2000
                        });
                        //页面跳转
                        //清空倒计时
                        window.sessionStorage.removeItem("3_verification");
                        //跳转登录页面
                        _self.$router.push({path:'/login'});
                        // this.loginUser();
                    }else {
                        if(body.resultMsg){
                            layer.msg(body.resultMsg);
                        }else{
                            layer.msg("注册失败");
                        }
                        _self.isShow = true;
                    }
                }),(response => {
                    layer.msg("注册异常");
                    _self.isShow = true;
                })
            },
            //登陆方法
            loginUser: function () {
                var _self = this;
                var params = {
                    phone:_self.phone,
                    password:'x1234567'
                };
                var body = {};
                body.params = params;
                var url = _self.utilHelper.apiUrl + "/api/login";
                _self.$http.post(url, body).then((response) => {
                    var data = response.body;
                    var result = data.result;
                    var errorMsg = data.errorMsg;
                    if (result == "1") {
                        window.localStorage.setItem("3_userId", data.resData.id);
                        window.localStorage.setItem("3_userName", data.resData.accountName);
                        window.localStorage.setItem("3_phone", data.resData.phone);
                        window.localStorage.setItem("3_isLogin", true);
                        window.localStorage.setItem("3_userRole", data.resData.userRoleId);
                        window.sessionStorage.setItem("3_isRegister","true");

                        _self.$router.replace({
                            path: '/index'
                        })
                    } else {
                        layer.msg(errorMsg, {
                            time: 1000
                        });
                    }
                }, (response) => {
                    layer.msg('登陆超时', {
                        time: 1000
                    });
                });
            },
            initMendian: function(){
                var _self = this;
                var params = {
                    companyCode: _self.companyCode,
                    mendian: '',
                    deptType: "1"
                }

                var body = {};
                body.params = params;
                var url = _self.utilHelper.apiUrl+'/api/getDeptByCompCode';
                _self.$http.post(url,body).then((response) => {
                    var body = response.body.resData;
                    _self.mendianList = body.deptList;
                }),(response => {
                    layer.msg("门店获取失败");
                })
            },
            initZubie: function(){
                var _self = this;
                _self.zubie = '';
                _self.zubieList = [];
                var params = {
                    companyCode: _self.companyCode,
                    mendian: _self.mendian,
                    deptType: "2"
                }
                var body = {};
                body.params = params;
                var url = _self.utilHelper.apiUrl+'/api/getDeptByCompCode';
                _self.$http.post(url,body).then((response) => {
                    var body = response.body.resData;
                    _self.zubieList = body.deptList;
                }),(response => {
                    layer.msg("组别获取失败");
                })
            },
            selectFile(){
                this.$refs.filElem.dispatchEvent(new MouseEvent('click'));
            },
            upload(){
                var file = this.$refs.filElem.files[0];
                var url = null ;
                var _self  = this;

                if (window.createObjectURL!=undefined) { // basic
                    url = window.createObjectURL(file) ;
                } else if (window.URL!=undefined) { // mozilla(firefox)
                    url = window.URL.createObjectURL(file) ;
                } else if (window.webkitURL!=undefined) { // webkit or chrome
                    url = window.webkitURL.createObjectURL(file) ;
                }

                qrcode.decode(url);
                qrcode.callback = function(imgMsg){
                    //解析到二维码内容
                    _self.analysisCode(imgMsg);
                }
            },
            getCompanyInfo(companyId,storeId,groupId){
                var _self = this;
                var params = {
                    companyId: companyId,
                    storeId:storeId,
                    groupId:groupId
                }

                var body = {};
                body.params = params;
                var url = _self.utilHelper.apiUrl+'/api/getCompanyInfo';
                _self.$http.post(url,body).then((response) => {
                    var body = response.body.resData;
                    if(body.result == 1){
                        _self.companyCode = body.code;
                        _self.mendianList = body.storeList;
                        _self.zubieList = body.groupList;
                        _self.mendian = storeId;
                        _self.zubie = groupId;
                    } else {
                        layer.msg('无法获取机构信息，请确认是否本司机构二维码');
                    }
                }),(response => {
                    layer.msg("公司获取失败");
                })
            },
            wxConfig(){
                //微信配置
                var currUrl=location.href.split('#')[0];
                var body = {};
                body.params={
                    url:currUrl
                };
                var url = this.utilHelper.apiUrl+'/api/js_ticket';
                this.$http.post(url,body).then((response)=>{
                    var data = response.body.resData;
                    wx.config({
                        debug: false,
                        appId: data.appid, // 必填，公众号的唯一标识
                        timestamp: data.time, // 必填，生成签名的时间戳
                        nonceStr: data.noncestr, // 必填，生成签名的随机串
                        signature: data.signature,// 必填，签名，见附录1
                        jsApiList: ['scanQRCode']
                    });
                });
            },
            scanQRCode:function(){
                //微信扫码
                var _self = this;
                wx.scanQRCode({
                    needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success: function (res) {
                        var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                        _self.analysisCode(result);
                    }
                });
            },
            analysisCode(imgMsg){
                if(!imgMsg || (imgMsg && imgMsg.indexOf('qudaowangRegister') == -1)) {
                    layer.msg('无法获取机构信息，请确认是否本司机构二维码');
                    return;
                }
                var _self = this;
                let url = imgMsg.substring(imgMsg.lastIndexOf("/")+1,imgMsg.length);
                let urls = url.split("|");
                let orgId = urls[1];
                if(urls.length > 2){
                    var storeId = urls[2];
                }
                if(urls.length > 3){
                    var groupId = urls[3]
                }
                _self.getCompanyInfo(orgId,storeId,groupId);
            }
        }
    }
</script>
<style scoped>
    .register{padding: 130px 20px 50px;height: 100%;}
    .register h3{text-align: center;font-size: 20px;margin-bottom: 80px;}
    .register-list li{border-bottom: 1px solid #ccc;padding: 6px 0 6px 16px;margin-bottom: 20px;}
    .register-list-row{position: relative;padding-left: 90px;padding-right:70px;height: 24px;line-height: 24px;}
    .register-row-title{position: absolute;left: 0;top: 0;width: 80px;color: #333;font-size: 16px;text-align: right;}
    .register-row-content{position: relative;}
    .register-row-content input{height: 24px;font-size: 14px;background-color: #f2f2f2;outline: none;padding-right: 30px;}
    .register-row-content .fa{position: absolute;right: 6px;top: 2px;font-size: 20px;color: #999;display: none;z-index: 1;}
    .register-row-content .fa-exclamation-circle{color: #bf0000;}
    .verification{position: absolute;right: 0;top: 0;width: 70px;height:24px;color: #333;font-size: 12px;text-align: right;background-color: #ff8b22; color: #fff;  text-align: center;  border-radius: 4px;}
    .verificationing{position: absolute;right: 0;top: 0;width: 70px;height:24px;color: #333;font-size: 12px;text-align: right;color: #ff8b22; background-color:#cacaca; text-align: center;  border-radius: 4px;}
    .btn-register{display: block;width: 100%;padding:12px 0;border:1px solid #ff7900;background-color: #f3ece6;color: #ff7900;margin-top: 50px; }
    .scan-btn{background: none;color:#F2574D;    position: absolute;right: 0;top: 0;width: 70px;height: 24px;font-size: 12px;text-align: right;padding: 2px;}
    .scan-btn img{height: 24px;}
    .fileBtn{display: none;}
</style>
